<template>
  <el-dialog
    v-model="dialogvisible"
    :width="width"
    custom-class="patrolDialog"
    :lock-scroll="false"
    :title="title || ''"
    @close="close"
  >
    <el-tabs v-model="activeName" @tab-click="handleTabClick">
      <el-tab-pane
        v-if="currentId == ''||(currentId!=''&&activeName == GUDINGRIQIJIHUA)"
        label="固定日期计划"
        :name="GUDINGRIQIJIHUA"
      >
        <BaseForm
          v-if="activeName == GUDINGRIQIJIHUA"
          ref="baseForm"
          :form-type="GUDINGRIQIJIHUA"
          :is-readonly="readonly"
          :default-value="dataForm"
          @setBaseParams="setBaseParams"
        />
      </el-tab-pane>
      <el-tab-pane
        v-if="currentId == ''||(currentId!=''&&activeName == YUFANGXINGJIHUA)" label="预防性计划" :name="YUFANGXINGJIHUA">
        <BaseForm
          v-if="activeName == YUFANGXINGJIHUA"
          ref="baseForm"
          :form-type="YUFANGXINGJIHUA"
          :is-readonly="readonly"
          :default-value="dataForm"
          @setBaseParams="setBaseParams"
        />
      </el-tab-pane>
      <el-tab-pane v-if="currentId == ''||(currentId!=''&&activeName == CHUFAXINGJIHUA)" label="触发性计划" :name="CHUFAXINGJIHUA">
        <BaseForm
          v-if="activeName == CHUFAXINGJIHUA"
          ref="baseForm"
          :form-type="CHUFAXINGJIHUA"
          :area-tree="areaTree"
          :is-readonly="readonly"
          :default-value="dataForm"
          @setBaseParams="setBaseParams"
        />
      </el-tab-pane>
    </el-tabs>

    <div
      v-if="activeName == GUDINGRIQIJIHUA || activeName == YUFANGXINGJIHUA"
      class="tableContainer"
    >
      <el-button
        v-if="!readonly"
        icon="iconfont icon--tainjia"
        :disabled="readonly"
        size="mini"
        type="primary"
        @click="addStep"
        >添加设备</el-button
      >
      <el-table
        ref="singleTable"
        class="stepTable"
        :data="dataForm.jobList"
        style="width: 100%"
      >
        <el-table-column prop="orderNumber" width="78" align="center" label="序号">
        </el-table-column>
        <el-table-column label="项目" width="240">
          <template #default="scope">
            <el-cascader
              v-if="!readonly"
              v-model="scope.row.projectId"
              style="width: 100%"
              :options="areaTree"
              :multiple="false"
              :show-all-levels="false"
              @change="id => projectIdChange(id, scope.row)"
            ></el-cascader>
            <div v-else class="selectText">{{ scope.row.projectName || scope.row.projectId }}</div>
          </template>
        </el-table-column>
        <el-table-column label="设备" width="240">
          <template #default="scope">
            <el-select
              v-if="!readonly"
              v-model="scope.row.deviceId"
              placeholder="请选择"
              filterable
              clearable
              style="width: 100%"
              @change="id => deviceChange(id, scope.row)"
            >
              <el-option label="请选择" value=""></el-option>
              <el-option
                v-for="(item, i) in deviceTypes"
                :key="i"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
            <div v-else class="selectText">
              {{ scope.row.deviceName || scope.row.deviceId }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="保养项目" width="240">
          <template #default="scope">
            <el-select
              v-if="!readonly"
              v-model="scope.row.standardId"
              clearable
              style="width: 100%"
              placeholder="请选择"
            >
              <el-option
                v-for="item in standardList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
            <div v-else class="selectText">
              {{ scope.row.standardName|| scope.row.standardId }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="备注" min-width="200">
          <template #default="scope">
            <input
              v-if="!readonly"
              v-model="scope.row.remark"
              type="text"
              class="workContentInput"
              placeholder="请输入"
            />
            <div v-else class="selectText">
              {{ scope.row.remark }}
            </div>
          </template>
        </el-table-column>
        <el-table-column v-if="currentId==''" label="操作" width="244">
          <template #default="scope">
            <el-button
              style="border: none"
              :disabled="readonly"
              type="text"
              class="iconfont icon-shangyi"
              size="small"
              :style="{
                color: '#4195F0'
              }"
              @click="setStep(scope.row, 'up')"
              >上移</el-button
            >
            <el-button
              style="border: none"
              :disabled="readonly"
              type="text"
              class="iconfont icon-xiayi"
              size="small"
              :style="{
                color: '#4195F0'
              }"
              @click="setStep(scope.row, 'down')"
              >下移</el-button
            >
            <el-button
              style="border: none"
              :disabled="readonly"
              type="text"
              class="iconfont icon-shanchu1"
              size="small"
              :style="{
                color: '#4195F0'
              }"
              @click="setStep(scope.row, 'del')"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div v-if="activeName == CHUFAXINGJIHUA" class="tableContainer">
      <el-button
        v-if="!readonly"
        icon="iconfont icon--tainjia"
        size="mini"
        type="primary"
        @click="addStep"
        >添加条件</el-button
      >
      <el-table
        ref="singleTable"
        class="stepTable"
        :data="dataForm.trigger ? dataForm.trigger.triggerList : []"
        style="width: 100%"
      >
        <el-table-column prop="orderNumber" width="78" align="center" label="序号">
        </el-table-column>

        <el-table-column label="属性" width="240">
          <template #default="scope">
            <el-select
              v-if="!readonly"
              v-model="scope.row.attr"
              placeholder="请选择"
              filterable
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="(item, i) in attrs"
                :key="i"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
            <div v-else class="selectText">
              {{ scope.row.attr }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="判断" width="240">
          <template #default="scope">
            <el-select
              v-if="!readonly"
              v-model="scope.row.condition"
              clearable
              style="width: 100%"
              placeholder="请选择"
            >
              <el-option
                v-for="(item, i) in conditions"
                :key="i"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
            <div v-else class="selectText">
              {{ scope.row.condition }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="值" min-width="200">
          <template #default="scope">
            <input
              v-if="!readonly"
              v-model="scope.row.value"
              type="text"
              class="workContentInput"
              placeholder="请输入"
            />
            <div v-else class="selectText">
              {{ scope.row.value }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="条件关系" width="240">
          <template #default="scope">
            <el-select
              v-if="!readonly"
              v-model="scope.row.relation"
              clearable
              style="width: 100%"
              placeholder="请选择"
            >
              <el-option
                v-for="(item, i) in relations"
                :key="i"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
            <div v-else class="selectText">
              {{ scope.row.relation }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="244">
          <template #default="scope">
            <el-button
              style="border: none"
              :disabled="readonly"
              type="text"
              class="iconfont icon-shanchu1"
              size="small"
              :style="{
                color: '#4195F0'
              }"
              @click="setStep(scope.row, 'del')"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <template #footer>
      <el-button size="mini" @click="close">取 消</el-button>
      <el-button v-if="!readonly" size="mini" type="primary" @click="submit">保 存</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts">
import _ from 'lodash'
import { v4 as uuidv4 } from 'uuid'
import BaseForm from './baseForm.vue'
import { getDeviceByType } from '@/api/device'
import { ref, reactive, toRefs, defineComponent, PropType, onMounted } from 'vue'
import useGlobal from '@/hooks/global/useGlobal'
import useProject from '@/hooks/project/useProject'
import { GUDINGRIQIJIHUA, YUFANGXINGJIHUA, CHUFAXINGJIHUA } from '@/common/constans/repair'
import { IPlan, IPlanJob, IPlanTrigger, IPlanTriggerListItem } from '@/common/types/repair/plan'
import { IStandard } from '@/common/types/repair/standard'
import { addRepairePlan, getRepairePlanDetail } from '@/api/repair/plan'
import { getAllRepairStandards } from '@/api/repair/standard'
import { removeSlash } from '@/utils/removeIdSlash'

export default defineComponent({
  components: { BaseForm },
  props: {
    width: {
      type: [String, Number],
      default: '60%'
    },
    visible: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: ''
    },
    close: {
      type: Function as PropType<() => void>,
      default: () => {
        // DO STH
      }
    },
    currentId: {
      type: String,
      default: ''
    },
    readonly: {
      type: Boolean,
      default: false
    }
  },
  setup(props, ctx) {
    const activeName = ref<string>(GUDINGRIQIJIHUA)
    const { $message, $confirm } = useGlobal()
    const dataForm = ref<IPlan>({
      id: '',
      name: '',
      type: '',
      executeTime: null,
      periodTime: 0,
      status: '',
      creator: '',
      createTime: null,
      deviceNameList: '',
      trigger: {
        id: '',
        mainId: '',
        detail: '',
        createTime: null,
        projectId: '',
        deviceId: '',
        triggerList: [] as IPlanTriggerListItem[],
        tenantId: ''
      } as IPlanTrigger,
      jobList: [] as IPlanJob[]
    })

    const state = reactive<{
      standardList: IStandard[]
      areaTree: NormalOption[]
      projectId: string
      dialogVisible: boolean
    }>({
      standardList: [],
      areaTree: [],
      projectId: '',
      dialogVisible: false
    })

    // const { getAreaTreeData } = useProject(props, ctx)

    const addStep = () => {
      if (activeName.value == GUDINGRIQIJIHUA || activeName.value == YUFANGXINGJIHUA) {
        dataForm.value.jobList.push({
          orderNumber: dataForm.value.jobList.length + 1,
          projectId: '',
          deviceId: '',
          standardId: '',
          remark: ''
        } as IPlanJob)
      } else if (activeName.value == CHUFAXINGJIHUA) {
        dataForm.value.trigger?.triggerList.push({
          orderNumber: dataForm.value.trigger.triggerList.length + 1,
          attr: '',
          condition: '',
          value: '',
          relation: ''
        } as IPlanTriggerListItem)
      }
    }
    const handleTabClick = (tab: any) => {
      dataForm.value.type = tab.props.name
      if (tab.props.name == GUDINGRIQIJIHUA || tab.props.name == YUFANGXINGJIHUA) {
        if (dataForm.value.jobList.length == 0) {
          addStep()
          dataForm.value.trigger && (dataForm.value.trigger.triggerList.length = 0)
        }
      } else if (tab.props.name == CHUFAXINGJIHUA) {
        if (dataForm.value.trigger?.triggerList.length == 0) {
          addStep()
          dataForm.value.jobList.length = 0
        }
      }
    }

    const setStep = (step: IPlanJob, option: string) => {
      if (option === 'up') {
        // orderNumber     >0
        if (~~step.orderNumber === 1) return
        dataForm.value.jobList[step.orderNumber - 2].orderNumber++
        dataForm.value.jobList[step.orderNumber - 1].orderNumber--
        dataForm.value.jobList.sort((a, b) => a.orderNumber - b.orderNumber)
      } else if (option === 'down') {
        if (~~step.orderNumber === dataForm.value.jobList.length) return
        dataForm.value.jobList[step.orderNumber].orderNumber--
        dataForm.value.jobList[step.orderNumber - 1].orderNumber++
        dataForm.value.jobList.sort((a, b) => a.orderNumber - b.orderNumber)
      } else if (option === 'del') {
        $confirm('确定要删除该任务吗?', '删除提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          dataForm.value.jobList.splice(step.orderNumber - 1, 1)
          dataForm.value.jobList.forEach(item => {
            if (item.orderNumber > step.orderNumber) {
              item.orderNumber--
            }
          })
        })
      }
    }

    const projectIdChange = async (id, row: IPlanJob) => {
      // row.projectId = row.projectId[row.projectId.length - 1]
      // row.deviceId = ''
      console.log(id, row)
    }

    const deviceTypeChange = async (id: string, row: any) => {
      row.deviceId = ''
      row.devices = []
      row.steps = []
      row.criterionId = ''
      const res = await getDeviceByType({ projectId: row.projectId, deviceType: id })
      row.devices = res.data.map(item => ({
        name: item.nodeName,
        id: item.nodeId
      }))
    }

    const deviceChange = (id: string, row: any) => {
      // row.steps = []
      // row.criterionId = ''
      // row.devices.forEach(async device => {
      //   if (device.id === id) {
      //     const res = await getAllRepairStandards('')
      //     row.steps = res.data.data.map(item => ({
      //       name: item.name,
      //       id: item.id
      //     }))
      //     return
      //   }
      // })
      console.log(id, row)
    }
    const { getAreaTreeData } = useProject(props, ctx)
    onMounted(async () => {
      const res = await getAllRepairStandards('')
      if (res.status == 200) {
        state.standardList = res.data
      }
      if (props.currentId.trim() == '') {
        addStep()
        dataForm.value.trigger && (dataForm.value.trigger.id = removeSlash(uuidv4()))
      } else {
        setDefaultData()
      }
      state.areaTree = await getAreaTreeData()
    })
    const setDefaultData = () => {
      getRepairePlanDetail(props.currentId)
        .then(res => {
          console.log(res)
          if (res.status == 200) {
            activeName.value = res.data.type
          }
          return Promise.resolve(res)
        })
        .then(res => {
          dataForm.value = res.data
        })
        .catch(() => {
          $message.warning('获取计划信息失败')
        })
    }

    const baseForm = ref<InstanceType<typeof BaseForm>>()

    const setBaseParams = (params: IPlan) => {
      dataForm.value.name = params.name
      dataForm.value.status = params.status
      if (activeName.value == GUDINGRIQIJIHUA) {
        dataForm.value.executeTime = params.executeTime
        dataForm.value.status = params.status
      } else if (activeName.value == YUFANGXINGJIHUA) {
        dataForm.value.executeTime = params.executeTime
        dataForm.value.periodTime = params.periodTime
      } else if (activeName.value == CHUFAXINGJIHUA) {
        if (dataForm.value.trigger) {
          dataForm.value.trigger.deviceId = params.trigger?.deviceId || ''
          dataForm.value.trigger.projectId = params.trigger?.projectId || ''
        }
      }
      // delete params.jobList
      // Object.assign(dataForm.value, params)
    }

    const submit = async () => {
      if (!baseForm.value?.checkRule()) {
        return false
      }
      const data = _.cloneDeep(dataForm.value)
      data.type = activeName.value
      if (activeName.value == GUDINGRIQIJIHUA || activeName.value == YUFANGXINGJIHUA) {
        data.jobList.map(item => {
          if (item.projectId.length > 0) {
            item.projectId = item.projectId.toString()
          }
        })
        if (data.jobList.length == 0) {
          $message.warning('请添加设备')
          return
        } else if (!data.jobList[0].projectId) {
          $message.warning('项目不能为空')
          return
        } else if (!data.jobList[0].deviceId) {
          $message.warning('设备不能为空')
          return
        } else if (!data.jobList[0].standardId) {
          $message.warning('保养项目不能为空')
          return
        }
      } else if (activeName.value == CHUFAXINGJIHUA) {
        if (data.trigger) {
          if (data.trigger.projectId.length > 0) {
            data.trigger.projectId = data.trigger.projectId.toString()
          }
          data.trigger.projectId
          if (data.trigger.triggerList.length == 0) {
            $message.warning('请添加条件')
            return
          } else if (!data.trigger.triggerList[0].attr) {
            $message.warning('属性不能为空')
            return
          } else if (!data.trigger.triggerList[0].condition) {
            $message.warning('判断不能为空')
            return
          } else if (!data.trigger.triggerList[0].value) {
            $message.warning('值不能为空')
            return
          } else if (!data.trigger.triggerList[0].relation) {
            $message.warning('条件关系不能为空')
            return
          }
        } else {
          $message.warning('数据异常')
          return
        }
      }
      try {
        const res = await addRepairePlan(data)
        if (res.status === 200) {
          $message.success('操作成功')
          props.close()
          ctx.emit('refreshData')
        } else {
          $message.error('请求失败')
        }
      } catch (err:any) {
        $message.error(err.data.message)
      }
    }
    const dialogvisible = ref<boolean>(props.visible)

    return {
      ...toRefs(state),
      dialogvisible,
      baseForm,
      activeName,
      dataForm,
      GUDINGRIQIJIHUA,
      YUFANGXINGJIHUA,
      CHUFAXINGJIHUA,
      submit,
      deviceChange,
      deviceTypeChange,
      projectIdChange,
      setStep,
      addStep,
      handleTabClick,
      setBaseParams,
      setDefaultData,
      deviceTypes: ref<string[]>(['其他', '管道', '物联网水表', 'PLC', '压力计']),
      attrs: ref<string[]>(['UA', 'IA', '设备运行时长']),
      conditions: ref([
        { label: '小于=', value: '<' },
        { label: '等于=', value: '=' },
        { label: '大于=', value: '>' }
      ]),
      relations: ref([
        { label: '且and', value: '&&' },
        { label: '或or', value: '||' }
      ])
    }
  }
})
</script>

<style lang="scss">
.patrolDialog {
  .el-dialog__body {
    padding: 0 !important;
  }
  .iconfont::before {
    margin-right: 5px;
  }
}
</style>
>

<style lang="scss" scoped>
.message-text {
  margin: 10px 0 12px 20px;
  color: #39b01c;
  line-height: initial;
}
.flexFromItem {
  display: flex;
  justify-content: space-between;
}
.baseForm {
  border-bottom: 1px solid #ebebeb;
  padding: 0 32px 12px;
}
.tableContainer {
  border-bottom: 1px solid #ebebeb;
  padding: 16px 32px 24px;
  .stepTable {
    margin-top: 16px;
    .selectText {
      background-color: #eeeeee;
      border-radius: 4px;
      line-height: 40px;
      width: 100%;
      height: 40px;
      border: 1px solid #dcdfe6;
      padding: 0 12px;
      overflow: hidden; //超出的文本隐藏
      text-overflow: ellipsis; //溢出用省略号显示
      white-space: nowrap; //溢出不换行
    }
  }
  .workContentInput {
    height: 40px;
    line-height: 40px;
    border: none;
    outline: none;
    width: 100%;
  }
}
</style>
